from django import template
from django.conf import settings

register = template.Library()


class BootstrapJSNode(template.Node):

    def __init__(self, args):
        self.args = set(args)

    def render(self, context):
        output = []
        if 'all' in self.args:
            if getattr(settings, 'TEMPLATE_DEBUG',):
                output = ['<script src="%sjs/bootstrap.js"></script>' % settings.STATIC_URL]
            else:
                output = ['<script src="%sjs/bootstrap.min.js"></script>' % settings.STATIC_URL]
        else:
            # popover requires tooltip
            if 'popover' in self.args:
                self.args.add('tooltip')
            output = ['<script src="%sjs/bootstrap-components/%s.js"></script>' % (settings.STATIC_URL, tag) for tag in self.args]
        return '\n'.join(output)


@register.tag
def bootstrap_js(parser, token):
    """ Returns Twitter Bootstrap (2.3.2) JavaScript file(s).
    all returns concatenated file; full file for TEMPLATE_DEBUG, minified otherwise.
    Other choice are:
        affix,
        alert,
        button,
        carousel,
        collapse,
        dropdown,
        modal,
        popover (adds tooltip if not included),
        scrollspy,
        tab,
        tooltip,
        transition.
    Individual files are not minified.
    """
    return BootstrapJSNode(token.split_contents()[1:])


@register.simple_tag
def jquery_js():
    min = '' if getattr(settings, 'TEMPLATE_DEBUG',) else '.min'
    output = ('<script src="%sjs/jquery%s.js"></script>' % (settings.STATIC_URL, min),
            '<script src="%sjs/jquery-migrate%s.js"></script>' % (settings.STATIC_URL, min),
            '<script src="%sjs/jquery-ui.effects%s.js"></script>' % (settings.STATIC_URL, min),
            '<script src="%sjs/jquery-ui.slider%s.js"></script>' % (settings.STATIC_URL, min),
    )
    return '\n'.join(output)


@register.simple_tag
def theme_css():
    theme = settings.BOOTSTRAP_THEME if hasattr(settings, 'BOOTSTRAP_THEME',) else 'default'
    min = '' if getattr(settings, 'TEMPLATE_DEBUG',) else '.min'
    output = ('<link rel="stylesheet" type="text/css" href="%scss/themes/%s/bootstrap%s.css">' % (settings.STATIC_URL, theme, min),
            '<link rel="stylesheet" type="text/css" href="%scss/font-awesome%s.css">' % (settings.STATIC_URL, min))
    return '\n'.join(output)


@register.simple_tag
def site_css():
    min = '' if getattr(settings, 'TEMPLATE_DEBUG',) else '.min'
    output = ('<link href="%ssite/css/all-fonts.css" rel="stylesheet">' % settings.STATIC_URL,
            '<link href="%ssite/css/site.css" rel="stylesheet">' % settings.STATIC_URL)
    return '\n'.join(output)


@register.simple_tag
def ie_js():
    output = ('<!--[if lt IE 9]>',
        '<script src="%sjs/assets/respond.min.js"></script>' % settings.STATIC_URL,
        '<script src="%sjs/assets/html5shiv.js"></script>' % settings.STATIC_URL,
        '<![endif]-->')
    return '\n'.join(output)